//
//  UserViewController.m
//  danpin
//
//  Created by chuangjia on 28/8/15.
//  Copyright (c) 2015 chuangjia. All rights reserved.
//

#import "UserViewController.h"

#import "MEExpandableHeaderView.h"
#import "viewconfig.h"
#import "CellConfig.h"
#import "ZShare.h"
#import "ZToastManager.h"
#import "UserInfoViewController.h"
#import "UserDetailViewController.h"
#import "CommentViewController.h"
#import "UserAdressViewController.h"
#import "messageconfig.h"
#import "orderconfig.h"
#import "CommentKeyBord.h"
#import "UMFeedbackViewController.h"
#import "UserInfo.h"
@interface UserViewController ()<UITableViewDataSource,UITableViewDelegate,UIAlertViewDelegate,UIActionSheetDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate,CommentKeyBordDelegate>
{
    
}
@property(strong,nonatomic) UITableView *tbView;
@property(strong,nonatomic) NSArray *tabArray;
@property(strong,nonatomic) NSArray *actionArray;
@property(strong,nonatomic) MEExpandableHeaderView *headerView;
@property(nonatomic,strong) NSString *userId;
@property(strong,nonatomic) UIImageView *iconView;
@property(strong,nonatomic) UILabel *fansLabel;
@property(strong,nonatomic) UILabel *levelLabel;
@property(strong,nonatomic) UIButton *qianDaoBtn;
@property(strong,nonatomic)UIImageView *dotMassageView;

@end

@implementation UserViewController
@synthesize isMe=_isMe;
@synthesize userDictionary=_userDictionary;
@synthesize fansLabel=_fansLabel;
@synthesize levelLabel=_levelLabel;
@synthesize qianDaoBtn=_qianDaoBtn;
@synthesize dotMassageView=_dotMassageView;
@synthesize isMessage=_isMessage;
- (id)init
{
    self = [super init];
    if (self)
    { }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor= UIColorFromRGB(0xf5f5f5);

    [UMengShare event:CK_ME acc:1];
    _tabArray = @[@[@"订单",@"余额",@"收货地址"],@[@"消息"],@[@"晒单",@"评论",@"喜欢",@"关注",@"粉丝"],@[@"积分",@"如何获得积分？"],@[@"不错，给个好评，加油！",@"有问题，点此反馈。"]];//,
    _actionArray = @[@[@"order",@"balance",@"address"],@[@"message"],@[@"shaidan",@"comment",@"like",@"follow",@"fans"],@[@"score",@"scorerule"],@[@"mark",@"feedback"]];

    self.userId =[[NSString stringWithFormat:@"%@",[[[ZShare sharedInstance] userInfo] objectForKey:@"user_id"]] replaceNullString];
    
    [self reloadData];
    [self initUI];
    [self notificationManager];
}
-(void)notificationManager
{
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(updateuserinfo:)
                                                 name:@"updateuserinfo"
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(updatebadge:)
                                                 name:@"updatebadge"
                                               object:nil];
    
}
-(void)updatebadge:(NSNotification*)notification
{
    self.isMessage = YES;
    [self.tbView reloadData];
    /// 返回Cell高度/* msg_type 0-评论 1-喜欢 2-关注 3-取消关注 4-@你说 5-私信你说 6-删除评论 11-推荐榜单 12-顶了单品
//    NSString *msg_type = (NSString *)notification.object;
}
-(void)updateuserinfo:(NSNotification*)notification
{
    if(self.headerView)
    {
        UIView* currentView = [_headerView viewWithTag:1000000];
        [currentView removeFromSuperview];
        currentView=nil;
        [self.headerView removeFromSuperview];
        self.headerView=nil;
        self.tbView.tableHeaderView = nil;
    }
    if(self.headerView)
    {
        [self.headerView removeFromSuperview];
        self.headerView=nil;
    }
    CGSize headerViewSize = CGSizeMake(self.view.bounds.size.width, hightAuto(233));
    UIView* currentView = [_headerView viewWithTag:1000000];
    [currentView removeFromSuperview];
    currentView=nil;
    _headerView= [[MEExpandableHeaderView alloc] initWithSize:headerViewSize
                                              backgroundImage:[UIImage imageNamed:@"my_background.png"]
                                                 contentViews:[self tableheadView]];
    self.tbView.tableHeaderView = _headerView;
    [self.tbView reloadData];
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.rootViewController.tabbar setHidden:NO];
    
}
-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.rootViewController.tabbar setHidden:YES];
}

-(void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    self.levelLabel=nil;
    self.fansLabel=nil;
    self.qianDaoBtn=nil;
    self.tabArray =nil;
    self.dotMassageView =nil;
    self.userDictionary=nil;
    if (_tbView) {
        _tbView.dataSource=nil;
        _tbView.delegate=nil;
        [_tbView removeFromSuperview];
        _tbView= nil;
    }
    [CommentKeyBord commentKeyboard].mDelegate=nil;
    [[CommentKeyBord commentKeyboard].mTextView resignFirstResponder];
    [[CommentKeyBord commentKeyboard].mTextView removeFromSuperview];
    [CommentKeyBord commentKeyboard].mTextView=nil;
    if(self.headerView)
    {
        UIView* currentView = [_headerView viewWithTag:1000000];
        [currentView removeFromSuperview];
        currentView=nil;
        [self.headerView removeFromSuperview];
        self.headerView=nil;
    }
    DLog(@"%s", __PRETTY_FUNCTION__);
}
-(void)reloadData
{
   [self refreshUserData];
}
-(void)scrollToTop
{
    if(_tbView)
    {
        [_tbView scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];
    }
}
//
-(void)initUI
{
    _tbView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height-hightAuto(45)) style:UITableViewStyleGrouped];
    _tbView.delegate = self;
    _tbView.dataSource = self;
    _tbView.backgroundColor =[UIColor clearColor];
    _tbView.showsVerticalScrollIndicator = NO;
    _tbView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    [self.view addSubview:_tbView];
    //
    if(self.headerView)
    {
        [self.headerView removeFromSuperview];
        self.headerView=nil;
    }
    CGSize headerViewSize = CGSizeMake(self.view.bounds.size.width, hightAuto(233));
    UIView* currentView = [_headerView viewWithTag:1000000];
    [currentView removeFromSuperview];
    currentView=nil;
    _headerView= [[MEExpandableHeaderView alloc] initWithSize:headerViewSize
                                              backgroundImage:[UIImage imageNamed:@"my_background.png"]
                                                 contentViews:[self tableheadView]];
    self.tbView.tableHeaderView = _headerView;
    NSString *version = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    NSString *msg = [NSString stringWithFormat:@"单品 V%@",version];
    self.tbView.tableFooterView =[ZShare footerView:msg];
    //
}
#pragma mark - tableview
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return _tabArray.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSArray* arr = (NSArray*)[_tabArray objectAtIndex:section];
    return  arr.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 44;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 10;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.01;
}

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = (UITableViewCell*)[tableView  dequeueReusableCellWithIdentifier:@""];
    if(cell == nil)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
    }
    if(indexPath.section >= _tabArray.count)
    {
        return cell;
    }
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    NSArray* arr = (NSArray*)[_tabArray objectAtIndex:indexPath.section];
    NSString *cellstr =[arr objectAtIndex:indexPath.row];
    cell.textLabel.text =cellstr;
    cell.textLabel.font = FONT(14);
    cell.textLabel.textColor = [UIColor grayColor];
    if ([cellstr isEqualToString:@"消息"] && self.isMessage == YES)
    {
        [cell addSubview:self.dotMassageView];
    }
    return cell;
}
-(UIImageView*)dotMassageView
{
    if (_dotMassageView) {
        [_dotMassageView removeFromSuperview];
        _dotMassageView=nil;
    }
    _dotMassageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"new_message_tip"]];
    _dotMassageView.frame=CGRectMake(50, 10, 10, 10);
    return _dotMassageView;
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    CGFloat sectionHeaderHeight = hightAuto(0);
    if (scrollView.contentOffset.y<=sectionHeaderHeight&&scrollView.contentOffset.y>=0) {
        scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0);
    } else if (scrollView.contentOffset.y>=sectionHeaderHeight) {
        scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, 0, 0);
    }
    if (scrollView == self.tbView)
    {
        [self.headerView offsetDidUpdate:scrollView.contentOffset];
    }
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSArray* arr = (NSArray*)[_tabArray objectAtIndex:indexPath.section];
    NSString *action =[arr objectAtIndex:indexPath.row];
 
    NSArray* actiony = (NSArray*)[_actionArray objectAtIndex:indexPath.section];
    NSString *actionyy =[actiony objectAtIndex:indexPath.row];
    if ([actionyy isEqualToString:@"order"]) {
        OrderListController *orderlist = [[OrderListController alloc] init];
        [self.navigationController pushViewController:orderlist animated:YES];
        orderlist=nil;
    }else if ([actionyy isEqualToString:@"balance"]) {
        
        BalanceViewController *balancelist = [[BalanceViewController alloc] init];
        [self.navigationController pushViewController:balancelist animated:YES];
        balancelist=nil;
        
    }else if ([actionyy isEqualToString:@"address"]) {
        UserAdressViewController *adress  =[[UserAdressViewController alloc] init];
        [self.navigationController pushViewController:adress animated:YES];
        adress=nil;
    }else if([actionyy isEqualToString:@"scorerule"])
    {
        UserScoreViewController *sco =[[UserScoreViewController alloc] init];
        [self.navigationController pushViewController:sco animated:YES];
        sco=nil;
    }else if([actionyy isEqualToString:@"mark"])
    {
        //去购买的统计页面
        NSMutableDictionary *dict =[NSMutableDictionary dictionary];
        [dict setValue:@"appstore_comment" forKey:@"action"];
        [dict setValue:@"" forKey:@"source"];
        [dict setValue:@"" forKey:@"type"];
        [dict setValue:@"" forKey:@"can_buy"];
        [BaseModel statbuypage:dict success:^(AFHTTPRequestOperation *operation, id result) {
            
        } failure:^(NSError *error) {
            
        }];
        
        NSString *str = @"itms-apps://itunes.apple.com/app/id1006667886";
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:str]];
        return;
    }else if([actionyy isEqualToString:@"feedback"])
    {
        UMFeedbackViewController *feedback = [[UMFeedbackViewController alloc] init];
        [self.navigationController pushViewController:feedback animated:YES];
        feedback = nil;
//        [self clickHelpEvent];
    }else if([actionyy isEqualToString:@"message"])
    {
        self.isMessage = NO;
        if (_dotMassageView) {
            [self.dotMassageView removeFromSuperview];
            self.dotMassageView=nil;
        }
        [self.rootViewController removeDotmessage];
        [self.tbView reloadData];
        [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
        MessagesViewController *msg =[[MessagesViewController alloc] init];
        [self.navigationController pushViewController:msg animated:YES];
        msg =nil;
    }else{
        UserDetailViewController *uDetail =[[UserDetailViewController alloc] init];
        uDetail.action =actionyy;
        uDetail.actionTitle =action;
        uDetail.userid=self.userId;
        [self.navigationController pushViewController:uDetail animated:YES];
        uDetail=nil;
    }
   
}
//用户反馈
-(void)clickHelpEvent
{
    [[CommentKeyBord commentKeyboard] textViewShowView:self commentKeyboardDelegate:self];
}
-(void)sendBtnClick:(UITextView *)textViewGet
{
    if (textViewGet.text.length==0) {
        return;
    }
    [UMengShare userFeedback:textViewGet.text];
}

-(void)cellAction:(BEventType)type views:(UIView *)v obj:(id)obj key:(id)key indexPath:(NSIndexPath *)indexPath
{
    switch (type) {
        case BEventType_comment:
        {
            NSString *pid =[NSString stringWithFormat:@"%@",[obj objectForKey:@"photo_id"]];
            CommentViewController *comm =[[CommentViewController alloc] init];
            comm.photo_id =pid;
            comm.dictionary =obj;
            [self.navigationController pushViewController:comm animated:YES];
        }
            break;
        case BEventType_userfollow:
        {
            if ([self isLogin]){
                NSString *pid =[NSString stringWithFormat:@"%@",[obj objectForKey:@"follow_id"]];
                NSString *nickname =[NSString stringWithFormat:@"%@",[obj objectForKey:@"follow_id"]];
                NSMutableDictionary *dict =[NSMutableDictionary dictionary];
                [dict setValue:@"follow_user" forKey:@"action"];
                [dict setValue:@"" forKey:@"brand_id"];
                [dict setValue:@"" forKey:@"cate_id"];
                [dict setValue:pid forKey:@"follow_id"];
                [dict setValue:nickname forKey:@"follow_name"];
                [dict setValue:@"" forKey:@"tag"];
                __weak typeof (self) wSelf = self;
                [UserInfo follow:dict success:^(AFHTTPRequestOperation* operation, id result){
                    
                    if (result&&[result isKindOfClass:[NSDictionary class]]) {
                        NSDictionary *resultDist =(NSDictionary*)result;
                        [[ZToastManager ShardInstance] showtoast:[resultDist objectForKey:@"msg"]];
                        [wSelf.tbView reloadData];
                    }
                    
                } failure:^(NSError* error){
                    [[ZToastManager ShardInstance] showtoast:@"取消关注失败"];
                }];
            }
        }
            break;
        default:
            break;
    }
}//

#pragma mark - UIScrollViewDelegate
//
-(UIView*)tableheadView
{
    if (_userDictionary==nil || [_userDictionary allKeys].count==0) {
         _userDictionary =[[ZShare sharedInstance] userInfo];
    }
   
    NSString *fanscount =[[NSString stringWithFormat:@"%@",[self.userDictionary objectForKey:@"fans_count"]] replaceNullString];
    NSString *followscount =[[NSString stringWithFormat:@"%@",[self.userDictionary objectForKey:@"follow_count"]]replaceNullString];
    NSString *scorecount =[[NSString stringWithFormat:@"%@",[self.userDictionary objectForKey:@"user_score"]]replaceNullString];
    NSString *user_balance =[[NSString stringWithFormat:@"%@",[self.userDictionary objectForKey:@"user_balance"]]replaceNullString];
    
    NSString *level =[[NSString stringWithFormat:@"%@",[self.userDictionary objectForKey:@"user_level"]]replaceNullString];
    NSString *check_in_days =[[NSString stringWithFormat:@"%@",[self.userDictionary objectForKey:@"check_in_days"]]replaceNullString];
    NSString *check_in_message =[[NSString stringWithFormat:@"%@",[self.userDictionary objectForKey:@"check_in_msg"]]replaceNullString];
    
    UIView *bgView =[[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, hightAuto(233))];
    bgView.backgroundColor =[UIColor clearColor];
    bgView.tag=1000000;
    
    UIButton *settingBtn =[UIButton buttonWithType:UIButtonTypeCustom];
    settingBtn.backgroundColor =[UIColor clearColor];
    settingBtn.tag=1;
    settingBtn.frame=CGRectMake(DEVICE_WIDTH -PHOTO_FRAME_WIDTH- widthAuto(31), PHOTO_FRAME_WIDTH*2+4, widthAuto(31), hightAuto(31));
    settingBtn.titleLabel.font =FONT(13);
    [settingBtn setImage:[UIImage imageNamed:@"setting.png"] forState:UIControlStateNormal];
    [settingBtn addTarget:self action:@selector(settingbtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [bgView addSubview:settingBtn];
    
    //
    UITapGestureRecognizer* singleRecognizer= [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTapFrom1)];
    _iconView =[[UIImageView alloc] initWithFrame:CGRectZero];
    _iconView.frame = CGRectMake((DEVICE_WIDTH-widthAuto(60))/2,YAuto(60), widthAuto(60), widthAuto(60));
    _iconView.layer.cornerRadius=widthAuto(30);
    _iconView.layer.masksToBounds = YES;
    _iconView.userInteractionEnabled =YES;
    
    NSString *middleFace =[[NSString stringWithFormat:@"%@",[self.userDictionary objectForKey:@"largeFace"]] replaceNullString];
    [_iconView sd_setImageWithURL:[NSURL URLWithString:middleFace] placeholderImage:[UIImage imageNamed:@"user_face.png"]];
    [_iconView addGestureRecognizer:singleRecognizer];
    [bgView addSubview:_iconView];
    singleRecognizer=nil;
    //
    _levelLabel =[[UILabel alloc] initWithFrame:CGRectZero];
    _levelLabel.frame = CGRectMake(_iconView.frame.origin.x+_iconView.frame.size.width/1.5,_iconView.frame.origin.y+_iconView.frame.size.height-PHOTO_FRAME_WIDTH*2, PHOTO_FRAME_WIDTH*3, PHOTO_FRAME_WIDTH*2);
    _levelLabel.backgroundColor = [UIColor blackColor];
    _levelLabel.textColor = [UIColor whiteColor];
    _levelLabel.textAlignment = NSTextAlignmentCenter;
    _levelLabel.layer.cornerRadius =PHOTO_FRAME_WIDTH;
    _levelLabel.layer.masksToBounds=YES;
    _levelLabel.font = [UIFont boldSystemFontOfSize:10];
    if (level.length==0) {
        level = @"0";
    }
    _levelLabel.text =[NSString stringWithFormat:@"%@级",level];
    _levelLabel.userInteractionEnabled =YES;
    [bgView addSubview:_levelLabel];
    
    //
    UILabel *nameLable =[[UILabel alloc] initWithFrame:CGRectZero];
    nameLable.frame = CGRectMake(0,_iconView.frame.origin.y+_iconView.frame.size.height+PHOTO_FRAME_WIDTH, DEVICE_WIDTH, PHOTO_FRAME_WIDTH*2);
    nameLable.backgroundColor = [UIColor clearColor];
    nameLable.textColor = [UIColor blackColor];
    nameLable.textAlignment = NSTextAlignmentCenter;
    nameLable.font = [UIFont boldSystemFontOfSize:14];
    nameLable.layer.shadowColor = [UIColor whiteColor].CGColor;
    nameLable.layer.shadowOffset = CGSizeMake(1,1);
    nameLable.layer.shadowOpacity = 0.3;
    nameLable.layer.shadowRadius = 0.3;
    nameLable.text =[self.userDictionary objectForKey:@"nick_name"];
    nameLable.userInteractionEnabled =YES;
    [bgView addSubview:nameLable];
    nameLable=nil;
    
    _fansLabel =[[UILabel alloc] initWithFrame:CGRectZero];
    _fansLabel.frame = CGRectMake(0,_iconView.frame.origin.y+_iconView.frame.size.height+PHOTO_FRAME_WIDTH*3.5, DEVICE_WIDTH, PHOTO_FRAME_WIDTH*2);
    _fansLabel.backgroundColor = [UIColor clearColor];
    _fansLabel.textColor = UIColorFromRGB(0x808080);
    _fansLabel.textAlignment = NSTextAlignmentCenter;
    _fansLabel.font = [UIFont boldSystemFontOfSize:12];
    _fansLabel.layer.shadowColor = [UIColor whiteColor].CGColor;
    _fansLabel.layer.shadowOffset = CGSizeMake(1,1);
    _fansLabel.layer.shadowOpacity = 0.3;
    _fansLabel.layer.shadowRadius = 0.3;

    if (followscount.length==0) {
        followscount = @"0";
    }
    if (fanscount.length==0) {
        fanscount = @"0";
    }
    if(scorecount.length==0)
    {
        scorecount =@"0";
    }
    if(user_balance.length==0)
    {
        user_balance =@"0";
    }
    _fansLabel.text =[NSString stringWithFormat:@"关注 %@ | 粉丝 %@ | 积分 %@ | 余额 %@",followscount,fanscount,scorecount,user_balance];
    _fansLabel.userInteractionEnabled =YES;
    [bgView addSubview:_fansLabel];
 
    
    _qianDaoBtn =[UIButton buttonWithType:UIButtonTypeCustom];
    _qianDaoBtn.backgroundColor =UIColorFromRGB(0xFF7900);
    _qianDaoBtn.frame=CGRectMake((DEVICE_WIDTH -widthAuto(140))/2, _fansLabel.frame.origin.y+_fansLabel.frame.size.height+PHOTO_FRAME_WIDTH, widthAuto(140), hightAuto(33));
    _qianDaoBtn.titleLabel.font =FONT(13);
    [_qianDaoBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    
    _qianDaoBtn.layer.cornerRadius = _qianDaoBtn.frame.size.height/2;
    _qianDaoBtn.layer.masksToBounds = YES;
    
    
    int checkdays = [check_in_days intValue];
    if (checkdays==0) {
        
         _qianDaoBtn.backgroundColor =UIColorFromRGB(0xFF7900);
        [_qianDaoBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
         [_qianDaoBtn setTitle:@"签到领积分" forState:UIControlStateNormal];
         [_qianDaoBtn addTarget:self action:@selector(qianDaoClick) forControlEvents:UIControlEventTouchUpInside];
    }else
    {
        if (check_in_message.length==0) {
            check_in_message=@"签到领积分";
        }
        NSDictionary *attribute = @{NSFontAttributeName:FONT(13)};
        
        CGSize retSize = [check_in_message boundingRectWithSize:CGSizeMake(DEVICE_WIDTH, 0)
                                                 options:NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin |NSStringDrawingUsesFontLeading
                                              attributes:attribute
                                                 context:nil].size;
        CGFloat with = retSize.width+PHOTO_FRAME_WIDTH*4;
        _qianDaoBtn.frame=CGRectMake((DEVICE_WIDTH -widthAuto(with))/2, _fansLabel.frame.origin.y+_fansLabel.frame.size.height+PHOTO_FRAME_WIDTH, widthAuto(with), hightAuto(33));
        [_qianDaoBtn setTitleColor:UIColorFromRGB(0x808080) forState:UIControlStateNormal];
        _qianDaoBtn.backgroundColor =UIColorFromRGB(0xcccccc);
        [_qianDaoBtn setTitle:check_in_message forState:UIControlStateNormal];
        
    }
    [bgView addSubview:_qianDaoBtn];
    return bgView;
}
//签到
-(void)qianDaoClick
{
    NSString *check_in_days =[[NSString stringWithFormat:@"%@",[self.userDictionary objectForKey:@"check_in_days"]]replaceNullString];
    if ([check_in_days intValue]==1) {
        return;
    }
    NSMutableDictionary *dict =[NSMutableDictionary dictionary];
    [dict setValue:@"check_in" forKey:@"action"];
    [dict setValue:[NSString stringWithFormat:@"%@",self.userId] forKey:@"user_id"];
    [dict setValue:@"0" forKey:@"from"];
    __weak typeof (self) wSelf = self;
    [UserInfo userCheckIn:dict success:^(AFHTTPRequestOperation *operation, id result) {
        if (result && [result isKindOfClass:[NSDictionary class]]) {
            NSDictionary *resultObject = (NSDictionary *)result;
            [[ZToastManager ShardInstance] showtoast:[resultObject stringForKey:@"msg"]];
            NSDictionary * score = [resultObject objectForKey:@"score"];
            if (score && [score isKindOfClass:[NSDictionary class]]) {
                NSString *title =[[NSString stringWithFormat:@"%@",[score objectForKey:@"check_in_msg"]] replaceNullString];
                if(title.length > 0)
                {
                    wSelf.qianDaoBtn.backgroundColor =UIColorFromRGB(0xcccccc);
                    NSDictionary *attribute = @{NSFontAttributeName:FONT(13)};
                    
                    CGSize retSize = [title boundingRectWithSize:CGSizeMake(DEVICE_WIDTH, 0)
                                                         options:NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin |NSStringDrawingUsesFontLeading
                                                      attributes:attribute
                                                         context:nil].size;
                    CGFloat with = retSize.width+PHOTO_FRAME_WIDTH * 4;
                    _qianDaoBtn.frame=CGRectMake((DEVICE_WIDTH -widthAuto(with))/2, _fansLabel.frame.origin.y+_fansLabel.frame.size.height+PHOTO_FRAME_WIDTH, widthAuto(with), hightAuto(33));
                    [_qianDaoBtn setTitleColor:UIColorFromRGB(0x808080) forState:UIControlStateNormal];
                    
                    
                    [wSelf.qianDaoBtn setTitle:title forState:UIControlStateNormal];
                }
                
                
//                NSDictionary *dict =[wSelf.userDictionary mutableCopy];
//                [dict setValue:@"1" forKey:@"check_in_days"];
//                NSString *scorecount =[[NSString stringWithFormat:@"%@",[resultObject objectForKey:@"user_score"]]replaceNullString];
//                NSString *level =[[NSString stringWithFormat:@"%@",[resultObject objectForKey:@"user_level"]]replaceNullString];
//                [dict setValue:scorecount forKey:@"user_score"];
//                [dict setValue:level forKey:@"user_level"];
//                wSelf.userDictionary =dict;
                //
                NSString *scoreMsg =[[score objectForKey:@"score_msg"] replaceNullString];
                if(scoreMsg && scoreMsg.length>0)
                {
                    [WTStatusBar setStatusText:scoreMsg timeout:3 animated:YES];
                }
                [wSelf refreshUserData];
                
            }
           
        }
    } failure:^(NSError *error) {
        
    }];
}
//
-(void)settingbtnClick:(id)sender
{
    UIButton *btn =(UIButton*)sender;
    switch (btn.tag) {
        case 0:
        {
            [self.navigationController popViewControllerAnimated:YES];
        }
            break;
        case 1:
        {
            UserInfoViewController *seeting =[[UserInfoViewController alloc] init];
            [self.navigationController pushViewController:seeting animated:YES];
        }
            break;
        case 2:
        {
            
        }
            break;
        default:
            break;
    }
    
}
-(void)handleSingleTapFrom1
{
    if (self.isMe){
        if ([self isLogin]) {
            UIActionSheet *actionSheet = [[UIActionSheet alloc]
                                          initWithTitle:nil
                                          delegate:self
                                          cancelButtonTitle:@"取消"
                                          destructiveButtonTitle:nil
                                          otherButtonTitles:@"拍照", @"相册选择",nil];
            actionSheet.actionSheetStyle = UIActionSheetStyleBlackOpaque;
            [actionSheet showInView:self.view];
        }
    }
}
-(void)handleSingleTapFrom2
{
    if (self.isMe){
        if ([self isLogin]) {
            
        }
    }
}

-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    switch (buttonIndex)
    {
        case 0:  //打开照相机拍照
            [self takePhoto];
            break;
        case 1:  //打开本地相册
            [self LocalPhoto];
            break;
    }
}
//开始拍照
-(void)takePhoto
{
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera])
    {
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.delegate = self;
        //设置拍照后的图片可被编辑
        picker.allowsEditing = YES;
        picker.sourceType = sourceType;
        [self presentViewController:picker animated:YES completion:nil];
    }else
    {
        DLog(@"模拟其中无法打开照相机,请在真机中使用");
        
    }
}

//打开本地相册
-(void)LocalPhoto
{
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    picker.delegate = self;
    //设置选择后的图片可被编辑
    picker.allowsEditing = YES;
    [self presentViewController:picker animated:YES completion:nil];
    
}
//当选择一张图片后进入这里
-(void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary *)info

{
    NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
    
    //当选择的类型是图片
    if ([type isEqualToString:@"public.image"])
    {
        //先把图片转成NSData
        UIImage* imageo = [info objectForKey:@"UIImagePickerControllerEditedImage"];
        
        //图片压缩，因为原图都是很大的，不必要传原图
        UIImage *image = [self scaleImage:imageo toScale:0.3];
        
        //关闭相册界面
        [picker dismissViewControllerAnimated:YES completion:nil];
        //图片保存的路径
        self.iconView.image = image;
        [self upLoadIcon:image name:nil];
    }
}
-(UIImage *)scaleImage:(UIImage *)image toScale:(float)scaleSize
{
    UIGraphicsBeginImageContext(CGSizeMake(image.size.width*scaleSize,image.size.height*scaleSize));
    [image drawInRect:CGRectMake(0, 0, image.size.width * scaleSize, image.size.height *scaleSize)];
    UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return scaledImage;
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    DLog(@"您取消了选择图片");
    [picker dismissViewControllerAnimated:YES completion:nil];
}
-(void)upLoadIcon:(UIImage *)image name:(NSString *)name
{
    [BaseModel userinfo:name image:image success:^(AFHTTPRequestOperation *operation, id resultObject) {
        
        [[ZToastManager ShardInstance] showtoast:[resultObject objectForKey:@"msg"]];
        if ([[resultObject objectForKey:@"code"] intValue]==1)
        {
            NSString *largeFace =[[NSString stringWithFormat:@"%@",[resultObject objectForKey:@"largeFace"]] replaceNullString];
            [[ZShare sharedInstance] initUserInfo:resultObject];
            [_iconView sd_setImageWithURL:[NSURL URLWithString:largeFace] placeholderImage:[UIImage imageNamed:@"user_face.png"]];
        }
    } failure:^(NSError *error) {
        DLog(@"您取消了选择图片---%@",error);
    }];
}
//
-(void)refreshUserData
{
    NSMutableDictionary *dict =[NSMutableDictionary dictionary];
    [dict setValue:@"index" forKey:@"action"];
    [dict setValue:[NSString stringWithFormat:@"%@",self.userId] forKey:@"user_id"];
    NSString *nickname =[[NSString stringWithFormat:@"%@",[self.userDictionary objectForKey:@"nick_name"]] replaceNullString];
    nickname = [nickname stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [dict setValue:nickname forKey:@"user_name"];
    [dict setValue:@"0" forKey:@"from"];
    __weak typeof (self) wSelf = self;
  
    [UserInfo homeV1:dict allowFetchCache:NO success:^(AFHTTPRequestOperation *operation, id result) {
        if (result && [result isKindOfClass:[NSDictionary class]]) {
            id user = [result objectForKey:@"user"];
            if (user && [user isKindOfClass:[NSDictionary class]]) {
              
                wSelf.userDictionary = user;
                NSString *check_in_days =[[NSString stringWithFormat:@"%@",[wSelf.userDictionary objectForKey:@"check_in_days"]]replaceNullString];
                NSString *check_in_message =[[NSString stringWithFormat:@"%@",[wSelf.userDictionary objectForKey:@"check_in_msg"]]replaceNullString];
                
                NSString *fanscount =[[NSString stringWithFormat:@"%@",[wSelf.userDictionary objectForKey:@"fans_count"]] replaceNullString];
                NSString *followscount =[[NSString stringWithFormat:@"%@",[wSelf.userDictionary objectForKey:@"follow_count"]]replaceNullString];
                NSString *scorecount =[[NSString stringWithFormat:@"%@",[wSelf.userDictionary objectForKey:@"user_score"]]replaceNullString];
                NSString *user_balance =[[NSString stringWithFormat:@"%@",[wSelf.userDictionary objectForKey:@"user_balance"]]replaceNullString];
                NSString *level =[[NSString stringWithFormat:@"%@",[wSelf.userDictionary objectForKey:@"user_level"]]replaceNullString];
               
                
                if (level.length==0) {
                    level=@"0";
                }
                wSelf.levelLabel.text =[NSString stringWithFormat:@"%@级",level];
                if (followscount.length==0) {
                    followscount = @"0";
                }
                if (fanscount.length==0) {
                    fanscount = @"0";
                }
                if (scorecount.length==0) {
                    scorecount=@"0";
                }
                if(user_balance.length==0)
                {
                    user_balance = @"0";
                }
                wSelf.fansLabel.text =[NSString stringWithFormat:@"关注 %@ | 粉丝 %@ | 积分 %@ | 余额 %@",followscount,fanscount,scorecount,user_balance];
                //
                
                int checkdays = [check_in_days intValue];
                if (checkdays==0) {
                    _qianDaoBtn.backgroundColor =UIColorFromRGB(0xFF7900);
                    [_qianDaoBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
                    [wSelf.qianDaoBtn setTitle:@"签到领积分" forState:UIControlStateNormal];
                    [wSelf.qianDaoBtn addTarget:wSelf action:@selector(qianDaoClick) forControlEvents:UIControlEventTouchUpInside];
                }else{
                    NSDictionary *attribute = @{NSFontAttributeName:FONT(13)};
                    
                    CGSize retSize = [check_in_message boundingRectWithSize:CGSizeMake(DEVICE_WIDTH, 0)
                                                         options:NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin |NSStringDrawingUsesFontLeading
                                                      attributes:attribute
                                                         context:nil].size;
                    CGFloat with = retSize.width+PHOTO_FRAME_WIDTH*4;
                    _qianDaoBtn.frame=CGRectMake((DEVICE_WIDTH -widthAuto(with))/2, _fansLabel.frame.origin.y+_fansLabel.frame.size.height+PHOTO_FRAME_WIDTH, widthAuto(with), hightAuto(33));
                    [_qianDaoBtn setTitleColor:UIColorFromRGB(0x808080) forState:UIControlStateNormal];
                     wSelf.qianDaoBtn.backgroundColor =UIColorFromRGB(0xcccccc);
                    [wSelf.qianDaoBtn setTitle:check_in_message forState:UIControlStateNormal];
                }
            }
        }
    } failure:^(NSError *error) {
        [ZShare hiddenAnimationView:wSelf.view text:@""];
    }];
}

@end
